// 1.获取全量的appkey
function getAppkey() {

    $.ajax({
        url : "/AopTest/create/getAppkeyList.do",
        type : "post",
        dataType : "json",
        success : function(result) {

            if (result.status == 0000) {
                var provinceList = result.data;
                addressInit(provinceList, 'provinceName', 'appkey', 'operator');
            }
            else {
                alert("code:" + result.status + ",detail:" + result.detail);
            }
        },
        error : function() {
            alert("系统异常,请稍后重试");
        }
    });
}

function closeAppkey() {

    var s = document.getElementById("shade");
    s.style.display = "none";

    var l = document.getElementById("appkeyarea");
    l.style.display = "none";
}

// 2.获取全量的接口名
function loadMethods() {
    $.ajax({
        url : "/AopTest/create/getMethodList.do",
        type : "post",
        dataType : "json",
        success : function(result) {
            if (result.status == 0000) {
                $(".methodlist").html("");
                var methodList = result.data;
                for ( var i = 0; i < methodList.length; i++) {
                    var input = '<input type="button" class="methodbut" name="' + methodList[i]
                            + '" onclick="getParamList(this)" value="' + methodList[i] + '"/>';
                    $(".methodlist").append(input);
                }
            }
            else {
                alert("code:" + result.status + ",detail:" + result.detail);
            }
        },
        error : function() {
            alert("系统异常,请稍后重试");
        }
    });
}

// 3.获取每个接口的页面以及接口对应的bizkey
function getParamList(a) {

    $a = $(a);
    var methodName = $a.val();
    $(".testMethodName").html(methodName);
    console.log(methodName);
    $.ajax({
        url : "/AopTest/create/getMethodPage.do",
        type : "post",
        data : {
            "methodName" : methodName
        },
        dataType : "json",
        success : function(result) {
            if (result.status == 0000) {
                $(".methodlist").hide();
                $(".showPage").html(result.data.htmlcontent);
                var bizkeys = result.data.bizkeys;
                var option = '<option value = "00">--请选择--</option>';
                for ( var i = 0; i < bizkeys.length; i++) {
                    var biekey = bizkeys[i];
                    option += '<option value =' + biekey + '>' + biekey + '</option>';
                }
                $("#bizkeys").html(option);
                // TODO:输出错误信息
                var exception = '';
                var excceptions = result.data.exception;
                for ( var i = 0; i < excceptions.length; i++) {
                    exception += excceptions[i] + "</br>";
                }
                if ('' != exception) {
                    alert(exception);
                }
                // 从数据库获取工号信息
                getOperInfoFromDB();
            }
            else {
                alert("code:" + result.status + ",detail:" + result.detail);
            }
        },
        error : function() {
            alert("系统异常,请稍后重试");
        }
    });
}

// 清除按钮
function clearPage() {
    $("#search").val("");
    // 重新加载列表,有简单方法,不想研究了...
    loadMethods();
    $(".methodlist").show();
    $(".showPage").html("");
    $(".testMethodName").html("");
    $(".result").html("");
}

function addParentDom(ele) {
    var copynodes = true;
    var nodes = ele.parentNode.parentNode;// 获取到父节点
    var clonedNode = nodes.cloneNode(copynodes);// 复制该节点
    var parentnodes = nodes.parentNode;// 找到指定元素的父元素
    if (parentnodes.lastChild == nodes) { // 判断指定元素的是否是节点中的最后一个位置
        // 如果是的话就直接使用appendChild方法
        parentnodes.appendChild(clonedNode, nodes);
    }
    else {
        parentnodes.insertBefore(clonedNode, nodes.nextSibling);
    }
    var thisclass = $e.parent().parent().attr("id");
    console.log(thisclass);
    $("#" + thisclass).append(copyHtml);
}

function hidechild(ele) {
    var nodes = ele.parentNode.parentNode;// 获取到父节点
    if (nodes.style.display == "block" || nodes.style.display == "") {
        nodes.style.display = "inherit";
        // 如果当前为显示状态需要将他的所有子节点隐藏(除去按钮所在的div)
        // 获取所有的子元素
        var childnodes = nodes.children;
        for ( var i = 1; i < childnodes.length; i++) {
            if ("LABEL" == childnodes[i].tagName || "INPUT" == childnodes[i].tagName || "DIV" == childnodes[i].tagName) {
                childnodes[i].style.display = "none";
            }
        }
        ele.src = "img/add.png";
    }
    else if (nodes.style.display == "inherit") {
        nodes.style.display = "block";
        // 如果当前为显示状态需要将他的所有子节点隐藏
        var childnodes = nodes.children;
        for ( var i = 0; i < childnodes.length; i++) {
            if ("LABEL" == childnodes[i].tagName || "INPUT" == childnodes[i].tagName || "DIV" == childnodes[i].tagName) {
                childnodes[i].style.display = "";
            }
        }
        ele.src = "img/reduce.png";
    }
}

// 4. 获取msg中的所有元素,拼装请求
function sendMsg(commoitButton) {
    var msgNode = commoitButton.parentNode.parentNode; // 获取msg的div节点
    var msg = '';
    var exception = '';
    // 获取各个请求
    var url = $("#selenvironmental").val();
    if ("0" == url) {
        alert("请先选择测试地址!");
        return;
    }
    var appkey = $("#appkey").val();
    if ("" == appkey) {
        alert("请选择接入方编码");
        return;
    }
    var bizkey = $("#bizkeys").val();
    if ("00" == bizkey) {
        alert("请选择业务编码");
        return;
    }
    var method = $(".testMethodName").text();
    if (msgNode.id == "msg") {// div是msg则开始处理 if (msgNode.id == "msg,Y") {
        var childnodes = msgNode.children;
        if (childnodes.length == 0) {
            alert("未获取到msg的信息");
            return;
        }
        var ret = createJson(msgNode, "Y", exception);
        msg = ret[0];
        exception = ret[1];
    }
    else {
        alert("未获取到要处理的节点信息,请确认");
        return;
    }
    console.log("msg:" + msg);
    // alert("msg:" + msg);
    if ('' != exception) {
        alert(exception.substring(1, exception.length));
        return;
    }

    $.ajax({
        url : "/AopTest/client/doClient.do",
        type : "post",
        dataType : "json",
        data : {
            "url" : url,
            "appkey" : appkey,
            "bizkey" : bizkey,
            "method" : method,
            "msg" : msg
        },
        success : function(result) {
            if (result.status == "0000") {
                $(".result").html(result.data);
            }
            else {
                alert("code:" + result.status + ",detail:" + result.detail);
            }
        },
        error : function() {
            alert("系统异常,请稍后重试");
        }
    });

}

// 递归进行请求拼装
function createJson(rootnode, rootCheckType, exception) {
    // 获取DIV下的元素
    var nodejson = '';
    var childnodes = rootnode.children;
    var lastMoreNodeId = '';
    for ( var i = 0; i < childnodes.length; i++) {
        var node = childnodes[i];
        var nodeParams = node.className.split(" ");
        var nodeId = node.id;
        var checkType = nodeParams[1];// 校验类型 *,+,Y,N
        if ("A" == node.tagName) {// 由A包围的输入框或者选择框
            node = node.children[0];// 输入框或者选择框
            checkType = node.className.split(" ")[1];
            nodeId = node.id;
            var value = node.value;
            if ("" == value || undefined == value || null == value) {
                if ("Y" == checkType && ("Y" == rootCheckType || "+" == rootCheckType)) {
                    exception += ";节点[" + rootnode.id.split(",")[0] + "]下的[" + nodeId + "]字段为必填值,不可为空";
                }
                continue;
            }
            var input = '"' + nodeId + '":"' + value + '",';
            nodejson += input;
        }
        else if ("DIV" == node.tagName && "" != nodeId && undefined != nodeId && null != nodeId) {
            var childRet = createJson(node, checkType, exception);
            var childJson = childRet[0];
            exception = childRet[1];
            if ('' != childJson) {
                if (nodeId == lastMoreNodeId) {// 跟前一个ID是同一个,证明是多节点的元素
                    childJson = childJson.split('[').join('');
                    childJson = childJson.split(']').join('');
                    nodejson = nodejson.substring(0, nodejson.length - 2) + ',' + childJson + '],';
                }
                else {
                    nodejson += '"' + nodeId + '":' + childJson;
                    lastMoreNodeId = nodeId;
                }
            }
        }
    }
    // 如果拼装了json串,则拼装该节点的外围节点
    if ('' != nodejson) {
        var nodeType = rootnode.className.split(" ")[1]; // 现在name属性取不到
        if ("+" == nodeType || "*" == nodeType) {
            nodejson = '[{' + nodejson + '}]';
        }
        else {
            nodejson = '{' + nodejson + '}';
        }
        if (rootnode.id != "msg") {// 只有不是msg的节点才才需要在最后加逗号 if (rootnode.id != "msg,Y") {
            nodejson += ',';
        }
        else {// 是msg的节点需要替换掉多余的逗号
            nodejson = nodejson.toString();
            nodejson = nodejson.split(',}').join('}');
            nodejson = nodejson.split(',]').join(']');
        }
    }
    var ret = new Array(2);
    ret[0] = nodejson;
    ret[1] = exception;
    return ret;
}

// function getName(e) {
//
// $e = $(e);
// var appkeyName = $e.val();
// $("#appkeyarea").hide();
// var appkeyInfo1 = document.getElementById("appkeyInfo1");
// var appkeyInfo2 = document.getElementById("appkeyInfo2");
// appkeyInfo1.style.display = "none";
// appkeyInfo2.style.display = "block";
// var s = document.getElementById("shade");
// s.style.display = "none";
// $("#appkeyname").text(appkeyName);
// }

// 5.修改联动菜单的值时重新获取工号的信息,并加载在生成好的接口页面上
function getOperatorInfo(lastOperatorId) {
    // 修改工号获取工号对应的信息
    $(".getOperatorId").change(function() {
        var operatorId = $("#operator").val();
        // console.log("result:" + (lastOperatorId != operatorId));
        if (lastOperatorId != operatorId) {
            console.log("operatorId:" + operatorId);
            // 从数据库获取工号信息
            getOperInfoFromDB(operatorId);
            return operatorId;
        }
    });
}

// 7.调用后台获取工号信息
function getOperInfoFromDB(operatorId) {
    // 调用后台获取工号信息
    if (operatorId == null || operatorId == undefined) {
        operatorId = $("#operator").val();
    }
    var oldOperId = $("#operator").data("operatorId");
    if (operatorId == oldOperId) {
        showOperatorInfo();
    }
    else {
        $.ajax({
            url : "/AopTest/create/getOperatorInfo.do",
            type : "post",
            data : {
                "operatorId" : operatorId
            },
            dataType : "json",
            success : function(result) {
                if ("0000" == result.status) {
                    // 设置对应的工号信息
                    var operatorInfo = result.data;
                    var province = operatorInfo.PROVINCE_CODE;
                    var city = operatorInfo.EPARCHY_CODE;
                    var district = operatorInfo.DISTRICT_ID;
                    var channelId = operatorInfo.CHANNEL_ID;
                    var channelType = operatorInfo.CHANNEL_TYPE_ID;
                    operatorId = operatorInfo.BSS_STAFF_ID;
                    $("#operator").data("province", province);
                    $("#operator").data("city", city);
                    $("#operator").data("district", district);
                    $("#operator").data("channelId", channelId);
                    $("#operator").data("channelType", channelType);
                    $("#operator").data("operatorId", operatorId);
                    console
                            .log("operatorInfo:[operatorId:" + operatorId + ",province:" + province + ",city:" + city
                                    + ",district:" + district + ",channelId:" + channelId + ",channelType:"
                                    + channelType + "]");
                    showOperatorInfo();
                }
                else {
                    alert("code:" + result.status + ",detail:" + result.detail);
                }
            },
            error : function() {
                alert("获取工号信息出错,请稍后重试");
            }
        });
    }
}

// 6.将工号信息显示在页面上
function showOperatorInfo() {
    // 从写入的值里获取
    $("#operatorId").val($("#operator").data("operatorId"));
    $("#province").val($("#operator").data("province"));
    $("#city").val($("#operator").data("city"));
    $("#district").val($("#operator").data("district"));
    $("#channelId").val($("#operator").data("channelId"));
    $("#channelType").val($("#operator").data("channelType"));
}

// 7.键盘监听事件
function keyboard() {
    var seach = $("#search");
    seach.keyup(function(event) {
        var seachText = $("#search").val();
        $(".methodbut").each(function(a, b) {
            var value = $(b).attr("value");
            if (value.indexOf(seachText) != -1) {
                $(b).show();
            }
            else {
                $(b).hide();
            }
        });
    });

    // appkey键盘事件
    var appkeyseach = $("#searchappkey");
    appkeyseach.keyup(function(event) {
        var seachText = $("#searchappkey").val();
        $(".appkey").each(function(a, b) {
            var value = $(b).attr("value");
            if (value.indexOf(seachText) != -1) {
                $(b).show();
            }
            else {
                $(b).hide();
            }
        });
    });
}
